package com.yjw.demo.pattern.singleton2;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;

public class EnumSingletonTest {

    public static void main(String[] args) {

        // serializeTest();

        reflectionTest();
    }

    private static void reflectionTest() {
        try {
            Class clazz = EnumSingleton.class;
            Constructor constructor = clazz.getDeclaredConstructor(String.class, int.class);
            constructor.setAccessible(true);
            EnumSingleton singleton = (EnumSingleton) constructor.newInstance("tom", "666");
            System.out.println(singleton);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void serializeTest() {
        EnumSingleton instance1 = null;
        EnumSingleton instance2 = EnumSingleton.getInstance();
        instance2.setData(new Object());

        try {
            //序列化
            FileOutputStream fos = new FileOutputStream("EnumSingletonTest.obj");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(instance2);
            oos.flush();
            oos.close();

            //反序列化
            FileInputStream fis = new FileInputStream("EnumSingletonTest.obj");
            ObjectInputStream ois = new ObjectInputStream(fis);
            instance1 = (EnumSingleton) ois.readObject();
            ois.close();

            System.out.println(instance1.getData());
            System.out.println(instance2.getData());
            System.out.println(instance1.getData() == instance2.getData());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}